let createError = require("http-errors");
let express = require("express");
let path = require("path");
let cors = require("cors");
let bodyParser = require("body-parser");
let cookieParser = require("cookie-parser");
let helmet = require("helmet");
let compression = require("compression");
let morgan = require("morgan");
var expressJWT = require("express-jwt");
let accessLogStream = require("./libs/logger");
let config = require("./libs/config");
let indexRouter = require("./routes/index");
let usersRouter = require("./routes/users");
var connectHistoryApiFallback = require('connect-history-api-fallback')
let app = express();


var request = require('request');

  




// 自定义token
morgan.token("userName", function (req, res) {
  return req.headers.username || "没登录";
});
// 自定义format，其中包含自定义的token
morgan.format(
  "useLog",
  '[user:] :userName :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status response-time/:response-time ms :res[content-length] ":referrer" ":user-agent"'
);

//链接数据库
let dbConnect = require("./db")();

// view engine setup 设置 模板引擎的存放目录与用的什么模板引擎
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

// 设置静态文件托管
app.use(express.static(path.join(__dirname, "public")));

app.use('/static',express.static(__dirname + '/dist/guangli/static'));
app.use('/tinymce',express.static(__dirname + '/dist/guangli/tinymce'));
app.get('/Management', function(req, res){
  res.sendFile(__dirname+'/dist/guangli/index.html');
});

app.use('/css',express.static(__dirname + '/dist/PC/css'));
app.use('/fonts',express.static(__dirname + '/dist/PC/fonts'));
app.use('/img',express.static(__dirname + '/dist/PC/img'));
app.use('/js',express.static(__dirname + '/dist/PC/js'));
app.get('/PCHome', function(req, res){
  res.sendFile(__dirname+'/dist/PC/index.html');
});
//Helmet是一系列帮助增强Node.JS之Express/Connect等Javascript Web应用安全的中间件。
app.use(helmet());
//跨域
app.use(cors());
// app.use(
//   cors({
//     origin: ["http://localhost:3001"],
//     methods: ["GET", "POST", "PUT", "DELETE"],
//     allowedHeaders: ["Content-Type", "Authorization"]
//   })
// );
//压缩请求 gzip是用于压缩，js、css等文件的压缩
app.use(compression());
// 为了支持 req.body 的使用
app.use(express.json());
app.use(
  express.urlencoded({
    extended: false
  })
);
// 为了获取 cookie
app.use(cookieParser());
app.use(bodyParser.json({ limit: '100mb' }));
app.use(bodyParser.urlencoded({ limit: '100mb', extended: true }));
// 设置静态文件托管
// app.use(express.static(path.join(__dirname, "public")));
app.use(
  morgan("useLog", {
    stream: accessLogStream
  })
);
app.use(morgan("tiny"));

//JWT令牌来验证HTTP请求
app.use(
  expressJWT({
    secret: config.secretOrPrivateKey
  }).unless({
    path: [
      "/api/v1/user_login",
      "/api/v1/user/login",
      "/api/v1/login",
      "/api/v1/registration",
      "/api/v1/forgetPwd",
      "/api/v1/PhoneMessage",
      "/api/v1/put_uploadImageTest",
      "/api/v1/uploadImageTest",
      "/api/v1/Task_completeTask",
      "/api/v1/uploadImagequestion",
      "/api/v1/uploadimg",
      "/api/v1/deleteadimg",
      "/api/v1/uploadtimyceimg",
      "/api/v1/user/info",
      "/api/v1/departmentlabel",
      "/get",
    ] //除了这个地址，其他的URL都需要验证
  })
);
//校验token失败时的处理
app.use(function (err, req, res, next) {
  console.log("headers:", req.url);
  if (req.url.indexOf("enclosure") > -1) {
    res.json({
      message: "找不到文件",
      code: 404,
      errer: err
    });
  }
  // console.log("err:", err);
  if (err.name === "UnauthorizedError") {
    //  这个需要根据自己的业务逻辑来处理（ 具体的err值 请看下面）
    console.error(req.path + ",无效token");
    res.json({
      message: "token过期，请重新登录",
      code: 400,
      errer: err
    });
  }
});

//挂载路由
// 设置 抽离出去的 路由文件的访问路径的前缀
// url 已 / 开头的，都会走到 indexRouter 中去。
app.use("/", indexRouter);
// url 已  /users 开头的，都会走到 usersRouter 中去
app.use("/users", usersRouter);
app.use("/", require("./routes/CRADROUTER.js"));
//上传
app.use("/", require("./routes/upload.js"));
app.use("/", require("./routes/registration.js")); //注册账号
app.use("/", require("./routes/forgetPwd")); //忘记密码
app.use("/", require("./routes/userAvatar")); //修改用户头像
// app.use("/", require("./routes/deleteImage")); // 删除图片接口
app.use("/", require("./routes/fwbimg")); //富文本图片
app.use("/", require("./routes/deleimg")); //删除图片
app.use("/", require("./routes/sendMessage")); //私信
app.use("/", require("./routes/resorcefj")); //附件上传
app.use("/", require("./routes/phoneMessage")); //验证码短信

// 删除接口
app.use("/", require("./routes/deleteTheInterface.js"));
//获取状态
app.use("/", require("./routes/getSituation"));
//登录
app.use("/", require("./routes/login.js"));
app.use("/", require("./routes/tasks.js")); //任务积分增加
app.use("/", require("./routes/managerlogin")); //后台管理员登陆
app.use("/", require("./routes/pcUploadImg")); //后台上传商品
app.use("/", require("./routes/comment")); //获取评论
app.use("/", require("./routes/exchangeGoods")); //兑换商品
app.use("/", require("./routes/tasks")); //积分任务
app.use("/", require("./routes/answer")); //获取答案
app.use("/", require("./routes/voteimgupload")); //上传投票
app.use("/", require("./routes/questionimgupload")); //上传投票
app.use("/", require("./routes/getproposal")); //小程序拉取问题
app.use("/", require("./routes/followarti"));
app.use("/", require("./routes/uploadimg")); //广告图上传
app.use("/", require("./routes/uploadtiymceimg")); //富文本图上传
app.use("/", require("./routes/onlineDraft")); //线上文章修改
app.use("/", require("./routes/searchData"));
app.use("/", require("./routes/getAttentionArtile")); //首页关注
app.use("/", require("./routes/getHot")); //首页热榜
app.use("/", require("./routes/deleencl"));
app.use("/", require("./routes/upvotimg"));
app.use("/", require("./routes/secCheck"));

// catch 404 and forward to error handler  404 文件的处理
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler 错误的处理
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});
// app.get( "/manager", function(request, response){
//   res.sendFile(__dirname + '/index.html')
// },);

module.exports = app;